package com.blogs.web.controller.admin;

import com.blogs.common.constant.LogActions;
import com.blogs.common.constant.WebConst;
import com.blogs.common.utils.APIResponse;
import com.blogs.common.utils.GsonUtils;
import com.blogs.domain.db.Options;
import com.blogs.service.log.LogService;
import com.blogs.service.option.OptionService;
import com.blogs.web.controller.BaseController;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auth hubiao
 */
@Api("系统设置管理")
@Slf4j
@Controller
@RequestMapping("admin/setting")
public class SettingController extends BaseController {


    @Resource
    private OptionService optionService;

    @Resource
    private LogService logService;


    @ApiOperation("进入设置页")
    @GetMapping(value = "")
    public String index(HttpServletRequest request, Model model) {
        List<Options> optionsList = optionService.getOptions();
        Map<String, String> options = Maps.newHashMap();
        optionsList.stream().forEach( (option) -> {
            options.put( option.getName(), option.getValue() );
        } );
        model.addAttribute( "options", options );
        return "admin/setting";
    }

    @ApiOperation("保存系统设置")
    @PostMapping(value = "")
    @ResponseBody
    public APIResponse saveSetting(HttpServletRequest request) {

        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            Map<String, String> querys = new HashMap<>();
            parameterMap.forEach( (key, value) -> {
                querys.put( key, join( value ) );
            } );

            optionService.saveOptions( querys );
            WebConst.initConfig = querys;

            // 写入日志
            logService.addLog( LogActions.SYS_SETTING.getAction(), GsonUtils.toJsonString( querys ), request.getRemoteAddr(), this.getUid( request ) );
            return APIResponse.success();

        } catch (Exception e) {
            String msg = "保存设置失败";
            return APIResponse.fail( e.getMessage() );
        }
    }

}
